package top.lingkang.ciyuanwaf.config;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import top.lingkang.ciyuanwaf.dto.ResponseResult;

/**
 * @author lingkang
 * created by 2023/10/16
 */
@Component
public class GlobalFilter implements Filter {
    private String err403 = new ResponseResult<>().fail("403").toJsonString();

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            String path = ctx.path();
            if (path.startsWith("/nginx") || path.startsWith("/file")) {
                if (ctx.session("isLogin") == null) {
                    if (ctx.header("User-Agent") == null)
                        ctx.outputAsJson(err403);
                    else
                        ctx.redirect("/login.html");
                    return;
                }
            }
            chain.doFilter(ctx);
            //此时：如果被处理
            if (!ctx.getHandled()) {
                //如果不需要再继承，就可以当 404 处理并返回了
                ctx.output("404");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            if (!(e instanceof NullPointerException))
                ctx.outputAsJson(new ResponseResult<>().fail(e.getMessage()).toJsonString());
            else
                ctx.outputAsJson(new ResponseResult<>().fail("服务器出错了").toJsonString());
        }

    }
}
